package com.example.controller;

import com.example.service.ZKService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class TestController implements InitializingBean {

  Logger logger = LoggerFactory.getLogger(getClass());

  @Resource private ZKService zkService;

  public static final String YYYY = "/yyyy";

  /**
   * * 设置临时节点并且设置监听
   *
   * @throws Exception
   */
  @RequestMapping("set")
  public String set() throws Exception {
    String id = "s" + System.currentTimeMillis();
    return this.zkService
        .getCuratorFramework()
        .create()
        .withTtl(60000)
        .creatingParentsIfNeeded()
        .withMode(CreateMode.PERSISTENT_WITH_TTL)
        .forPath(YYYY + "/" + id, id.getBytes());
  }

  /**
   * * 获取节点过期时间
   *
   * @param id
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "getTLL")
  public long getTLL(String id) throws Exception {
    return this.zkService
        .getCuratorFramework()
        .checkExists()
        .forPath(YYYY + "/" + id)
        .getEphemeralOwner();
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    this.zkService.watchNode(
        YYYY,
        new PathChildrenCacheListener() {
          @Override
          public void childEvent(
              CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent)
              throws Exception {
            if (pathChildrenCacheEvent.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
              logger.warn("node add: " + pathChildrenCacheEvent.getData().getPath());
            }
            if (pathChildrenCacheEvent.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) {
              logger.warn("node delete: " + pathChildrenCacheEvent.getData().getPath());
            }
          }
        });
  }
}
